<script setup lang="ts">
import { getRoleDetailAPI, getRoleListAPI, getRoleUserAPI, getTreeListAPI } from '@/apis/system';
import type { Role, RoleData, RoleUser } from '@/types/system';
import { ref,computed,onMounted,reactive } from 'vue';
// 导入两张图片
import userIcon from '@/assets/user.svg'
import userIconActive from '@/assets/user-active.svg'
import type { TreeInstance } from 'element-plus';
import router from '@/router'; // 假设你的路由配置文件在 src/router/index.ts
import { useRoute } from 'vue-router';


// 定义 userTotal 计算属性
const userTotal = computed(() => roleUserList.value.length)

const roleList = ref<Role[]>([])
// 1. 获取角色列表
const getRoleList = async () => {
  const res = await getRoleListAPI()
  roleList.value = res.data
  // 获取第一个角色详情
  const roleId = res.data[0].roleId
  getRoleDetail(roleId)
  // 获取第一个角色的成员
  getRoleUser(roleId)
}
getRoleList()

// 2. 点击激活交互
const activeIndex = ref(0)
const changeRole = async (index: number, roleId: number) => {
  // 2.1 设置高亮效果
  activeIndex.value = index
  // 2.2 获取角色详情
  // const res = await getRoleDetailAPI(roleId)
  // console.log('res', res);
  getRoleDetail(roleId)
  // 2.3 获取角色成员
  getRoleUser(roleId)
}

// 3. 获取权限列表(树形)
const treeList = ref<RoleData[]>([])
const getTreeList = async () => {
  const res = await getTreeListAPI()
  // console.log('res', res);
  treeList.value = res.data
}
getTreeList()
// 4. 获取角色详情
const perms = ref<number[][]>([])
const treeRefs = ref<TreeInstance[]>([])
const getRoleDetail = async (roleId: number) => {
  const res = await getRoleDetailAPI(roleId)
  console.log('res', res);
  perms.value = res.data.perms
}

  // 切换时，设置树形组件选中
  treeRefs.value.forEach((tree, index) => {
    // 选中节点，setCheckedKeys 优先级高于 default-checked-keys(默认占位)
    tree.setCheckedKeys(perms.value[index])
  })

  // 5. tab切换
  const activeTabName = ref<'tree' | 'member'>('tree') // 默认打开tree

  // 6. 获取角色成员
const roleUserList = ref<RoleUser[]>([])
const getRoleUser = async (roleId: number) => {
  const res = await getRoleUserAPI(roleId)
  roleUserList.value = res.data.rows
}


const onCommand = (command: string, roldId: number)=>{
  if (command === 'edit'){
    router.push(`/roleAdd?id=${roldId}`)
  }
}

// 回填信息
// 0. 编辑缓存roleId
const route = useRoute()
const roldId = computed(() => {
  return route.query.id as string
})
onMounted(() => {
  // 如果有id，就是编辑角色
  if (roldId.value) {
    editRoleDetail()
  }
})

// 定义 roleForm
const roleForm = reactive<{
  perms: number[][];
  remark: string;
  roleId: number;
  roleName: string;
}>({
  perms: [],
  remark: '',
  roleId: 0,
  roleName: ''
})

const editRoleDetail = async () => {
  const res = await getRoleDetailAPI(Number(roldId.value))
  const { perms, remark, roleId, roleName } = res.data
  // 回填基础表单
  Object.assign(roleForm, { perms, remark, roleId, roleName })  // 回填Tree
   treeRefs.value.forEach((tree, index) => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-expect-error
    tree.setCheckedKeys(roleForm.value.perms[index])
  })
}

</script>
  
<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div v-for="(item,index) in roleList" 
      :key="item.roleId" 
      @click="changeRole(index, item.roleId)"
      :class="{ 'active': index == activeIndex }" 
      class="role-item"
      >
        <div class="role-info">
          <img :src="index == activeIndex? userIconActive : userIcon " class="icon" />
          {{ item.roleName }}
        </div>
        <div class="more">
          <el-dropdown @command="onCommand($event, item.roleId!)">
            <span class="el-dropdown-link">
              <img src="@/assets/more.svg" class="icon" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>编辑角色</el-dropdown-item>
                <el-dropdown-item>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="small" @click="$router.push('/roleAdd')">添加角色</el-button>
    </div>
     <!-- 右侧权限和成员 -->
     <div class="right-wrapper">
      <el-tabs v-model="activeTabName">
        <el-tab-pane label="功能权限" name="tree">
      <div class="tree-wrapper">
        <!-- 角色权限列表 -->
        <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
          <div class="tree-title"> {{ item.title }} </div>
          <!-- 树形组件 -->
          <el-tree 
          :data="item.children" 
            :props="{ label: 'title', disabled: () => true }" 
            default-expand-all
            show-checkbox
            :default-checked-keys="perms[index]"
            node-key="id"
            ref="treeRefs"
          />
        </div> 
      </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员(${userTotal})`" name="member">
          成员管理表格
          <div class="user-wrapper">
            <el-table :data="roleUserList">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
        </el-tab-pane>
        </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;
  background-image: url('@/assets/v2-b972660b4d0bfeba831d05236682bf35_r.jpg'); /* 替换为你的图片路径 */
  background-size: cover; /* 背景图片覆盖整个元素 */
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  height: 100vp; /* 使背景图片高度占满整个视口 */
  width: 1517px; /* 使背景图片宽度占满整个视口 */
  position: relative; /* 确保背景图片的定位 */

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }
     
    .more {
      display: flex;
      align-items: center;
      .icon {
          width: 15px;
        }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    :deep() .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>